from fastapi import HTTPException
from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
from app.models.user import User
from app.core.local_logging import setup_logging

logger = setup_logging()


class UserRepository:
    """用户数据访问层（类似Java DAO）"""

    def __init__(self, db: Session):
        self.db = db

    def get_by_username(self, username: str) -> User | None:
        """根据用户名查询用户"""
        return self.db.query(User).filter(User.username == username).first()

    def save(self, user: User) -> User:
        """保存用户到数据库"""
        try:
            self.db.add(user)
            self.db.commit()
            self.db.refresh(user)  # 刷新以获取数据库生成的ID
            return user
        except SQLAlchemyError as e:
            self.db.rollback()
            logger.error(f"保存用户失败: {str(e)}")
            raise HTTPException(status_code=400, detail=f"数据库错误: {str(e)}")

    def delete(self, username: str) -> bool:
        """根据用户名删除用户"""
        user = self.get_by_username(username)
        if not user:
            return False
        self.db.delete(user)
        self.db.commit()
        return True

    def get_all(self) -> list[User]:
        """获取所有用户"""
        return self.db.query(User).all()
